// Editor: myBigPro9/src001/main/java/org/csu/mybigpro/service/DocumentAnalysisService.java
// Action: Create
package org.csu.mybigpro.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.csu.mybigpro.DTO.SolvedQuestionDto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

@Service
public class DocumentAnalysisService {

    private static final Logger log = LoggerFactory.getLogger(DocumentAnalysisService.class);

    @Autowired
    private WordParserService wordParserService;

    @Autowired
    private AiService aiService;

    private final ObjectMapper objectMapper = new ObjectMapper();

    public List<SolvedQuestionDto> analyzeDocument(MultipartFile documentFile) throws Exception {
        // 步骤1: 从Word文档提取全文
        String fullText = wordParserService.extractText(documentFile);
        if (fullText == null || fullText.isBlank()) {
            throw new Exception("Word文档中没有内容或无法读取。");
        }
        log.info("Word文档全文提取成功，总字数: {}", fullText.length());

        // 步骤2: 调用AI将全文拆分成题目列表 (包含对AI响应的正确解析)
        String rawQuestionsResponse = aiService.splitTextIntoQuestions(fullText);
        JsonNode rootNode = objectMapper.readTree(rawQuestionsResponse);
        String questionsJsonText = rootNode.path("candidates").path(0).path("content").path("parts").path(0).path("text").asText();
        JsonNode questionsNode = objectMapper.readTree(extractJsonContent(questionsJsonText));

        List<String> questionList = StreamSupport.stream(questionsNode.spliterator(), false)
                .map(JsonNode::asText)
                .collect(Collectors.toList());
        log.info("AI成功将文档拆分成 {} 道题目", questionList.size());

        // 步骤3: 遍历每一道题，直接调用AI进行解答
        List<SolvedQuestionDto> results = new ArrayList<>();
        int questionNumber = 1;
        for (String question : questionList) {
            log.info("开始处理第 {} 道题: {}", questionNumber, question.substring(0, Math.min(question.length(), 50)));
            try {
                // 调用简化的解题流程
                String solution = solveSingleQuestion(question);
                results.add(new SolvedQuestionDto(question, solution));
                log.info("第 {} 道题处理成功", questionNumber);
            } catch (Exception e) {
                log.error("处理第 {} 道题时发生错误: {}", questionNumber, e.getMessage());
                results.add(new SolvedQuestionDto(question, "处理此题时发生错误：" + e.getMessage()));
            }
            questionNumber++;
        }

        return results;
    }

    /**
     * 【全新简化流程】直接让AI根据问题文本进行解答
     */
    private String solveSingleQuestion(String questionText) throws Exception {
        // 1. 创建一个直接的prompt，要求AI解答问题
        String prompt = String.format(
                "你是一位专业的解题教师，拥有丰富的知识库。请根据以下题目，直接给出一个详细、严谨、分步骤的解答。你的解答应该清晰易懂，并可以包含必要的公式。请直接开始解答，不要有任何客套话。\n\n" +
                        "【问题】:\n%s\n\n" +
                        "【你的详细解答】:",
                questionText
        );

        // 2. 调用AI服务生成内容
        String finalAnswerJson = aiService.generateContent(
                List.of(Map.of("role", "user", "parts", List.of(Map.of("text", prompt)))),
                null,
                null
        );

        // 3. 解析AI的响应并返回最终答案
        return objectMapper.readTree(finalAnswerJson)
                .path("candidates").path(0)
                .path("content").path("parts").path(0)
                .path("text").asText("AI未能生成解答。");
    }

    // JSON提取辅助方法 (保持不变)
    private String extractJsonContent(String rawResponse) {
        String trimmedResponse = rawResponse.trim();
        if (trimmedResponse.startsWith("```json")) {
            return trimmedResponse.substring(7, trimmedResponse.lastIndexOf("```")).trim();
        }
        int startIndex = trimmedResponse.indexOf('[');
        int endIndex = trimmedResponse.lastIndexOf(']');
        if (startIndex != -1 && endIndex != -1) {
            return trimmedResponse.substring(startIndex, endIndex + 1);
        }
        return rawResponse;
    }
}